//
//  PassWordLoginController.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/4/23.
//

import UIKit

class PassWordLoginController: ZsBaseViewController {

    var countryCodeModel:WLCountryCode?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_ForgetPassword), style: UIBarButtonItem.Style.plain, target: self, action: #selector(resetPassword))
        
        self.setUI()

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if (self.countryCodeModel?.phonecode.count ?? 0) <= 0 {
            self.configurationInfo()
        }
    }
    
    func setUI() {
        self.view.addSubview(self.logoImg)
        self.view.addSubview(self.importPhoneView)
        self.view.addSubview(self.importPassWord)
        self.view.addSubview(self.loginBtn)

        self.logoImg.snp.makeConstraints { (maker) in
            maker.top.equalTo(self.view.snp.topMargin).offset(46)
            maker.height.equalTo(100)
            maker.width.equalTo(100)
            maker.centerX.equalTo(self.view.snp.centerX)
        }
        self.importPhoneView.snp.makeConstraints { (maker) in
            maker.top.equalTo(self.logoImg.snp.bottom).offset(10)
            maker.height.equalTo(45)
            maker.left.equalToSuperview().offset(25)
            maker.right.equalToSuperview().offset(-25)
        }
        self.importPassWord.snp.makeConstraints { (maker) in
            maker.top.equalTo(self.importPhoneView.snp.bottom).offset(10)
            maker.height.equalTo(45)
            maker.left.equalToSuperview().offset(25)
            maker.right.equalToSuperview().offset(-25)
        }
        self.loginBtn.snp.makeConstraints { (make) in
            make.top.equalTo(self.importPassWord.snp.bottom).offset(30)
            make.left.equalTo(self.view.snp.left).offset(25)
            make.right.equalTo(self.view.snp.right).offset(-25)
            make.height.equalTo(45)
        }
    }
    
    func configurationInfo() {
        let userInfoDefaults = UserDefaults.standard
        let week:NSInteger = NSCalendar.current.ordinality(of: .weekday, in: .year, for: NSDate.init() as Date)!
        var weekValue:NSInteger = userInfoDefaults.integer(forKey: WLUserModel.getPhone() + ActionHeader.WLSmsCountry)
        if weekValue != week {
            HttpService.sharedHttpService().getSmsCountrySuccess { (state, countryCode) in
                if (state) {
                    UserDefaults.standard.setValue(week, forKey: WLUserModel.getPhone()+ActionHeader.WLSmsCountry)
                    self.countryCodeModel = countryCode
                    self.importPhoneView.selectCountryCodeBrn.setTitle(self.countryCodeModel?.phonecode, for: .normal)
                }
            }
        } else {
            let model:Array<WLCountryCode> = CacheTool.cacheTool.searchCountryCodes()
            if (model.count > 1) {
                self.countryCodeModel = model.first
                self.importPhoneView.selectCountryCodeBrn.setTitle(self.countryCodeModel?.phonecode, for: .normal)
            }
        }
        weekValue = UserDefaults.standard.integer(forKey: WLUserModel.getPhone() + ActionHeader.WLMyanmarArea)
        if (weekValue == week ) {
            HttpService.sharedHttpService().getMyanmarAreaSuccess { (state) in
                if state {
                    UserDefaults.standard.setValue(week, forKey: WLUserModel.getPhone() + ActionHeader.WLMyanmarArea)
                }
            }
        }
    }
    
    
    @objc func resetPassword() {
        let resetPassC = SetPassViewController()
        resetPassC.isResPassword = true
        self.navigationController?.pushViewController(resetPassC, animated: true)
    }
    
    @objc func clickLoginBtn() {
        if self.importPhoneView.importAccount.text?.count ?? 0 <= 0 {
            self.view.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_hint_phone_not))
            return
        }
        if self.importPassWord.importAccount.text?.count ?? 0 <= 0 {
            self.view.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_hint_passWord_not))
        return
        }
        if self.countryCodeModel?.phonecode.count ?? 0 <= 0 {
            self.configurationInfo()
            return
        }
        let deviceUUID = UIDevice.current.identifierForVendor?.uuidString
        var loginDic:[String:String] = ["phone":self.importPhoneView.importAccount.text!,
                        "password":self.importPassWord.importAccount.text!,
                        "phonecode":(self.countryCodeModel?.phonecode ?? "") as String,
                        "deviceType":"DEVICE_TYPE_IOS","deviceId":deviceUUID!]
        self.view.makeToastActivity(.center)
        HttpService.sharedHttpService().loginWithPassWord(dicData: loginDic) { (Json, state, error) in
            if state {
                let code = Json["code"].int
                if code == 106 {
                    let alertt = UIAlertController.init(title: nil, message: ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.hint_phoneRegister), preferredStyle: .alert)
                    let cancel = UIAlertAction.init(title: ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_cancel), style: .default) { (UIAlertAction) in
                        
                    }
                    cancel.setValue(UIColor.init(hexString: "#333333"), forKey: "titleTextColor")
                    let goRegister = UIAlertAction.init(title: ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_register), style: .default) { (UIAlertAction) in
                        let loginVC = HostLoginController.init()
                        let naVC = ZsNavigationController.init(rootViewController: loginVC)
                        Constants.window?.rootViewController = naVC
                        Constants.window?.makeKeyAndVisible()
                    }
                    alertt.addAction(cancel)
                    alertt.addAction(goRegister)
                    self.present(alertt, animated: true) {
                        
                    }
                } else {
                    WLUserModel.saveUser(jsonDic: Json)
                    self.getUserInfo()
                }
            } else {
                self.view.hideToastActivity()
                self.view.makeToast(error)
            }
        }
    }

    
    
    lazy var logoImg:UIImageView = {
        let logoImg = UIImageView.init(image: UIImage.init(named: "login_Logo"))
        
        return logoImg
    }()
    
    lazy var importPassWord:ImportPassWordView = {
        let importPassWord = ImportPassWordView()
        importPassWord.importAccount.text = "123456"
        return importPassWord
    }()
    
    lazy var loginBtn:UIButton = {
        let loginBtn = UIButton()
        loginBtn.setTitle(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_Login), for: .normal)
        loginBtn.backgroundColor = UIColor.init(hexString: "#FFD10A")
        loginBtn.setTitleColor(UIColor.init(hexString: "#333333"), for: .normal)
        loginBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        loginBtn.layer.cornerRadius = 5
        loginBtn.addTarget(self, action: #selector(clickLoginBtn), for: .touchUpInside)
        return loginBtn
    }()
    
    lazy var importPhoneView:ImportPhoneView = {
        let importPhoneView = ImportPhoneView()
        importPhoneView.importPhoneBlock = {
            if (self.countryCodeModel != nil) {
                Constants.window?.addSubview(self.selectCountryView)
            } else {
                self.configurationInfo()
            }
        }
        importPhoneView.importAccount.text = "13011111111"
        return importPhoneView
    }()

    lazy var selectCountryView:SelectCountryView = {
        let selectCountryView = SelectCountryView.init(frame: CGRect.init(x: 0, y: 0, width: Constants.screenWidth, height: Constants.screenHeight))
        selectCountryView.selectCountryViewBlock = { countryCode in
            self.countryCodeModel = countryCode
            self.importPhoneView.selectCountryCodeBrn.setTitle(self.countryCodeModel?.phonecode, for: .normal)
        }
        selectCountryView.refreshData()
        return selectCountryView
    }()
}
